<template>
  <view class="honor-detail">
    <text class="absolute-title"> 企业荣誉 </text>
    <!-- #ifdef H5 -->
    <AppShare isHerf :desc="curEnterpriseName" title="企业荣誉" />
    <!-- #endif -->
    <enterprise-base-info-card
      :enterprise-info="enterpriseInfo"
      :bottom-buttons="enterpriseCardBtns"
      @bottom-btn-click-emit="handleBottomBtnClick"
    />
    <honor-box
      class="enterprise-honor-box"
      :current-idx="1"
      :honor-title="`${enterpriseHonorTotal}项企业荣誉`"
      :tab-list="enterpriseHonorTabs"
      @tab-click="handleEnterpriseHonorTabClick"
    >
      <view v-if="enterpriseHonorList?.length > 0" class="honor-list">
        <!-- <view
          class="honor"
          @click="getPassHonor"
          v-for="(honor, idx) in enterpriseHonorList"
          :key="idx"
        >
          <text class="honor_text">
            {{ honor }}
          </text>
        </view> -->
        <enterprise-tag
          :label-data="enterpriseHonorList"
          @handle-tag-click="handleTagClick"
        />
      </view>
      <up-empty v-else mode="data" text="企业暂无该级别荣誉" textSize="28rpx" />
    </honor-box>

    <honor-box
      class="enterprise-badge-box"
      :honor-title="`${enterpriseBadgeTotal}项企业勋章`"
      :tab-list="enterpriseBadgeTabs"
      @tab-click="handleEnterpriseBadgeTabClick"
    >
      <view v-if="enterpriseBadgeList?.length > 0" class="honor-badge-list">
        <view
          class="badge"
          v-for="(badge, idx) in enterpriseBadgeList"
          :key="idx"
          @tap="handleBadgeClick(badge)"
        >
          <image class="badge-img" mode="widthFix" :src="badge.badgeImageUrl" />
          <text class="badge-text">
            {{ badge.badgeName }}
          </text>
        </view>
      </view>
      <up-empty v-else mode="data" text="企业暂无该级别徽章" textSize="28rpx" />
    </honor-box>

    <view class="honor-charts">
      <Radar
        :width="700"
        :height="500"
        id="htzyRadarId"
        :categories="radarCategories"
        :chartData="radarChartData"
      />
      <rank-line
        id="xsssss"
        :width="700"
        :totalScore="rank.totalScore"
        :honorScoreList="rank.honorScoreList"
      />
    </view>

    <honor-box
      class="honor-dim-box"
      :show-title="false"
      @tab-click="handleHonorDimTabClick"
      :tab-list="honorDimensionalityTabs"
    >
      <view class="text-content">
        <text class="text">该维度荣誉已有</text>
        <text class="h4">{{ curDimHonorTotal }}个</text>
      </view>
      <text class="other-text" @tap="routeToTalentTreePage"
        >点击查看推荐荣誉
      </text>
      <tag :label-data="curDimTagsList"  />
      <!-- @handle-tag-click="handleTagClick" -->
    </honor-box>
  </view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import {
  generateRandomNumId,
  getUrlParamsInH5,
  getUrlParamsInWeixin,
  wxSetUpShareFunction,
} from "@/utils/utils";
import {
  getEnterpriseAllHonorListApi,
  getEnterpriseAllInfoApi,
  getEnterpriseBadgeDetailApi,
  getEnterpriseHonorMapApi,
  getEnterPriseHonorRadarChartDataApi,
} from "@/package_honour/pages/api/honor-detail";
import enterpriseBaseInfoCard from "./components/enterprise-base-info-card.vue";
import honorBox from "./components/honor-box.vue";
import Radar from "@/package_honour/pages/honour/components/radar.vue";
import RankLine from "@/package_honour/pages/honour/components/rank-line.vue";
import Tag from "@/package_honour/pages/honour/components/tag.vue";
import enterpriseTag from "@/package_honour/pages/honour/components/enterprise-tag.vue";
import AppShare from "@/components/appShare/index.vue";
import { customNav } from "@/utils/customNav";
const { proxy } = getCurrentInstance();
const enterpriseCardBtns = [
  {
    btnText: "企业详情",
  },
  {
    btnText: "元宇宙空间",
  },
];

const curEnterpriseId = ref(""); /* 当前企业id */
const curEnterpriseName = ref(""); /* 当前企业名称 */
const enterpriseInfo = ref({}); /* 企业详情 */
/**
 * 获取企业信息
 * @returns {Promise<void>}
 */
const getEnterpriseInfo = async () => {
  const res = await getEnterpriseAllInfoApi(curEnterpriseId.value);
  const { code, data } = res;
  if (code === 200) {
    enterpriseInfo.value = data;
    console.log("enterpriseInfo.value", enterpriseInfo.value);
    //
    curEnterpriseName.value = enterpriseInfo.value.enterpriseName;
    console.log("curEnterpriseName.value", curEnterpriseName.value);
    await getRadarChartData();
    await gatEnterpriseAllHonor();
    await getEnterpriseHonorTabs();
    await getEnterpriseBadgeDetail();
  }
};

const handleBottomBtnClick = (btn) => {
  switch (btn.btnText) {
    case "企业详情":
      customNav(
        `enterprise-detail?id=${curEnterpriseId.value}&enterpriseName=${curEnterpriseName.value}`
      );
      break;
    case "元宇宙空间":
      proxy.$unity3dGlobal();
      break;

    default:
      break;
  }
};

const enterpriseHonorTabs = ref([]); /* 企业荣誉tabs */
const enterpriseHonorList = ref([]); /* 企业当前荣誉列表 */
const enterpriseHonorTotal = ref(0); /* 企业荣誉总数 */
/**
 * 获取企业荣誉tabs数据
 * @returns {Promise<void>}
 */
const getEnterpriseHonorTabs = async () => {
  const res = await getEnterpriseHonorMapApi();
  const { code, data } = res;
  let count = 0;
  if (code === 200) {
    const { enterpriseHonorGroupGardeMap } = enterpriseInfo.value || {};

    const honorCountDataList = Object.keys(enterpriseHonorGroupGardeMap).map(
      (key) => {
        count += enterpriseHonorGroupGardeMap[key].length;
        return {
          honorLevel: key,
          honorDetails: enterpriseHonorGroupGardeMap[key],
          honorCount: enterpriseHonorGroupGardeMap[key].length,
        };
      }
    );
    enterpriseHonorTabs.value = data.map((item, idx) => {
      return {
        name: item,
        value: idx,
        badge: {
          value: honorCountDataList.find((honor) => honor.honorLevel === item)
            ?.honorCount,
        },
      };
    });
    enterpriseHonorTotal.value = count;
    enterpriseHonorList.value = enterpriseHonorGroupGardeMap["国家级"];
  }
};

/**
 * 监听企业荣誉tab点击事件
 * @param curTab
 */
const handleEnterpriseHonorTabClick = (curTab) => {
  let honorLevel;
  honorLevel = curTab.name;
  const { enterpriseHonorGroupGardeMap } = enterpriseInfo.value;

  enterpriseHonorList.value = enterpriseHonorGroupGardeMap[honorLevel];
  console.log(honorLevel);
};

const enterpriseBadgeTabs = ref([]); /* 企业勋章tabs */
const enterpriseAllBadgeList = ref([]);
const enterpriseBadgeList = ref([]); /* 企业当前荣誉列表 */
const enterpriseBadgeTotal = ref(0); /* 企业荣誉总数 */
const getEnterpriseBadgeDetail = async () => {
  const res = await getEnterpriseBadgeDetailApi(curEnterpriseName.value);
  const { code, data } = res;
  if (code === 200) {
    const { badgeTypeList, badgeDetailList } = data;
    enterpriseAllBadgeList.value = badgeDetailList;
    enterpriseBadgeTotal.value = badgeDetailList.length;
    enterpriseBadgeTabs.value = badgeTypeList.map((badge, idx) => {
      return {
        name: badge.badgeTypeName,
        value: idx,
        badge: {
          value: badgeDetailList.filter(
            (item) => item.badgeTypeName === badge.badgeTypeName
          ).length,
        },
      };
    });
    enterpriseBadgeList.value = badgeDetailList.filter(
      (badge) => badge.badgeTypeId === "1"
    );
  }
};

/**
 * 监听企业荣誉tab点击事件
 * @param curTab
 */
const handleEnterpriseBadgeTabClick = (curTab) => {
  const { name: badgeTypeName } = curTab;
  enterpriseBadgeList.value = enterpriseAllBadgeList.value.filter(
    (badge) => badge.badgeTypeName === badgeTypeName
  );
};

const handleBadgeClick = (badge) => {
  const badgeType = badge?.badgeTypeName;
  if (badgeType === "成长徽章")
    return customNav(`badge-detail?badgeDetail=${JSON.stringify(badge)}`);
};

/* 雷达图数据 */
const radarChartData = ref([
  {
    name: "该企业指数",
    data: [],
  },
  {
    name: " 参考指数",
    data: [],
  },
]);
const radarCategories = ref([]);
const rank = reactive({
  totalScore: 0,
  honorScoreList: [],
});
//点击荣誉标签跳转
const getPassHonor = () => {};
/**
 * 获取雷达图数据
 * @returns {Promise<void>}
 */
const getRadarChartData = async () => {
  const params = curEnterpriseName.value;
  const res = await getEnterPriseHonorRadarChartDataApi(params);
  const { code, data } = res;
  if (code === 200) {
    const {
      honorScoreEntity,
      honorScoreMaxVo,
      totalScore,
      honorScoreStageConfigEntity,
    } = data || {};
    console.log("honorScoreEntity", honorScoreEntity);
    console.log("honorScoreMaxVo", honorScoreMaxVo);
    console.log("totalScore", totalScore);
    console.log("honorScoreStageConfigEntity", honorScoreStageConfigEntity);
    const gradeMap = {
      创新发展: "cxfzGrade",
      公司治理: "gszlGrade",
      社会责任: "ppzrGrade",
      安全生产: "lsscGrade",
      团队建设: "tdjsGrade",
      市场营销: "scyxGrade",
    };
    const dimListMap = {
      创新发展: "cxfzList",
      公司治理: "gszlList",
      社会责任: "shzrList",
      安全生产: "aqscList",
      团队建设: "tdjsList",
      市场营销: "scyxList",
    };
    const gradeArr = ["C", "B", "A", "A+", "S"];
    const average = honorScoreEntity;
    honorDimensionalityTabs.value = honorScoreMaxVo.map((dim, idx) => {
      return {
        name: dim.dimensionName,
        value: idx,
        key: dimListMap[dim.dimensionName],
      };
    });
    Array.isArray(honorScoreMaxVo) &&
      honorScoreMaxVo.forEach((dimension) => {
        let grade = data[gradeMap[dimension.dimensionName]] || "";
        let gradeAverage = average[gradeMap[dimension.dimensionName]] || "";
        console.log("gradeAverage", gradeAverage);
        radarCategories.value.push(dimension.dimensionName + "\n" + grade);
        let allScore = gradeArr.findIndex((item) => item === grade) + 1;
        let averageScore =
          gradeArr.findIndex((item) => item === gradeAverage) + 1;
        radarChartData.value[0].data.push((allScore * 2) / 10);
        radarChartData.value[1].data.push((averageScore * 2) / 10);
      });
    console.log("radarCategories", radarCategories.value);
    console.log("radarChartData", radarChartData.value);
    rank.totalScore = totalScore || 0;
    rank.honorScoreList = honorScoreStageConfigEntity || [];
  }
};

const honorDimensionalityTabs = ref([]); /* 荣誉维度tabs */
const curDimHonorTotal = ref(0); /* 当前维度已有荣誉总数 */
const allHonorData = ref({}); /* 所有荣誉数据 */
const curDimTagsList = ref([]); /* 当前tab下的荣誉列表 */
/**
 * 获取所有维度的荣誉数据
 * @returns {Promise<void>}
 */
const gatEnterpriseAllHonor = async () => {
  const res = await getEnterpriseAllHonorListApi(curEnterpriseName.value);
  const { code, data } = res;
  if (code === 200) {
    allHonorData.value = data;
    const defaultDim = honorDimensionalityTabs?.value[0]?.key;
    curDimTagsList.value = data[defaultDim];
    curDimHonorTotal.value =
      Array.isArray(data[defaultDim]) &&
      data[defaultDim].filter((dim) => dim.isExist).length;
  }
};

/**
 * 监听维度荣誉tab点击事件
 * @param tab
 */
const handleHonorDimTabClick = (tab) => {
  const tabKey = tab.key;
  curDimTagsList.value = allHonorData.value[tabKey];
  curDimHonorTotal.value = allHonorData.value[tabKey].filter(
    (dim) => dim.isExist
  ).length;
};

const routeToTalentTreePage = () => {
  customNav("talent-tree?enterpriseId=" + curEnterpriseId.value);
};
const handleTagClick = (data) => {
  console.log(data);
  // #ifdef H5 || APP-PLUS
  customNav(`recommend?url=${data.link}`);
  // #endif
};
// onShow(() => {
//   uni.pageScrollTo({
//     scrollTop: 0,
//     duration: 0,
//   });
//   /* #ifndef MP-WEIXIN */
//   curEnterpriseId.value = getUrlParamsInH5()?.id;
//   // curEnterpriseName.value = getUrlParamsInH5()?.name;
//   /* #endif */
//   /* #ifdef MP-WEIXIN */
//   curEnterpriseId.value = getUrlParamsInWeixin()?.id;
//   // curEnterpriseName.value = getUrlParamsInWeixin()?.name;
//   /* #endif */
//   // console.log("curEnterpriseId.value",curEnterpriseId.value);
//   // console.log("curEnterpriseName.value", curEnterpriseName.value);
//   getEnterpriseInfo();
//   //
// });

onLoad(() => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0,
  });
  /* #ifndef MP-WEIXIN */
  curEnterpriseId.value = getUrlParamsInH5()?.id;
  // curEnterpriseName.value = getUrlParamsInH5()?.name;
  /* #endif */
  /* #ifdef MP-WEIXIN */
  curEnterpriseId.value = getUrlParamsInWeixin()?.id;
  // curEnterpriseName.value = getUrlParamsInWeixin()?.name;
  /* #endif */
  // console.log("curEnterpriseId.value",curEnterpriseId.value);
  // console.log("curEnterpriseName.value", curEnterpriseName.value);
  getEnterpriseInfo();
  /* #ifdef MP-WEIXIN */
  wxSetUpShareFunction(
    `/package_honour/pages/honour/enterprise-honor-detail?name=${curEnterpriseName.value}&&typeName=企业&&id=${curEnterpriseId.value}`
  );
  /* #endif */
});
</script>
<style scoped lang=less>
.honor-detail {
  background: @honor-detail-bg;
  background-size: 750rpx 357rpx;
  background-color: @color-white;
  padding-top: 180rpx;

  .absolute-title {
    position: absolute;
    top: 2%;
    left: 50%;
    transform: translateX(-50%);
    font-family: "ali-p";
    font-weight: 500;
    color: @color-origin-white;
    font-size: 31rpx;
    letter-spacing: 2rpx;
  }
  .enterprise-honor-box {
    margin-top: 35rpx;
    :deep(.honor-list) {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      .honor {
        width: calc(50% - 11rpx);
        height: 80rpx;
        line-height: normal;
        text-align: center;
        border-radius: 3rpx;
        border: 1px solid @color-green;
        font-family: "ali-p";
        font-size: 23rpx;
        color: @color-green-text;
        margin-bottom: 20rpx;
        // overflow: hidden;
        // text-overflow: ellipsis;
        // white-space: nowrap;
        display: flex;
        flex-flow: row nowrap;
        justify-content: center;
        align-items: center;
        .honor_text {
          display: inline-block;
        }
      }
    }
  }

  .enterprise-badge-box {
    margin-top: 30rpx;
    :deep(.honor-badge-list) {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
      gap: 5rpx;
      padding-top: 10rpx;

      .badge {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: calc(33.3% - 40rpx);
        margin-top: 30rpx;

        &-img {
          width: 137rpx;
          height: 167rpx;
        }

        &-text {
          font-family: "ali-p";
          font-weight: 500;
          font-size: 23rpx;
          line-height: 35rpx;
          color: @color-black-text;
          margin-top: 18rpx;
        }
      }
    }
  }

  .honor-charts {
    background-color: @color-origin-white;
    margin-top: 30rpx;
    padding: 0 31rpx 18rpx 31rpx;
  }

  .honor-dim-box {
    margin-top: 30rpx;

    :deep(.other-text) {
      margin-top: 23rpx;
      font-family: "ali-l";
      font-size: 23rpx;
      font-weight: 400;
      color: @color-blue-text;
    }

    :deep(.text-content) {
      margin-top: 50rpx;
      display: flex;
      font-family: "ali-l";
      letter-spacing: 2rpx;
      font-size: 31rpx;

      .text {
        color: #68696a;
      }

      .h4 {
        font-family: "ali-m";
        margin-left: 5rpx;
        color: #00b588;
      }
    }
  }
}
</style>
